<?php

require_once(__DIR__.'/../../../../wp-load.php');

function exit_with($msg) {
    header('HTTP/1.0 401 Unauthorized');
    header('Content-Type: application/json');
    echo json_encode([
        'code' => 401,
        'error' => $msg
    ]);
    exit;
}

function response_with($data) {
    header('Content-Type: application/json');
    echo json_encode([
        'code' => 200,
        'data' => $data
    ]);
    exit;
}

if(!get_option('users_can_register')) {
    exit_with('对不起，本站暂不开放注册。');
}

$name = trim($_POST['user_name']);
$email = trim($_POST['user_email']);
$pass = trim($_POST['user_pass']);
$pass2 = trim($_POST['user_pass_2']);

$mobile = trim($_POST['user_mobile']);
$mobile_code = trim($_POST['user_mobile_code']);


if (!$name) {
    exit_with('用户名不能为空');
}

if (!$email) {
    exit_with('邮箱不能为空');
}

if (!$pass || !$pass2) {
    exit_with('密码不能为空');
}

if ($pass != $pass2) {
    exit_with('两次输入的密码不同');
}

if(!is_email($email)) {
    exit_with('邮箱形式有问题，请检查或换一个通用邮箱。');
}

$verify = get_option('verify:'.$mobile);
if (!$verify) {
    exit_with('验证码错误，请重新获取验证码。');
}

if ($verify['code'] != $mobile_code) {
    exit_with('验证码错误');
}

if ($verify['time'] < time() - 10*60000) {
    exit_with('验证码已过期，请重新获取验证码。');
}

$userdata = array(
  'user_login' => $name,
  'user_pass'  => $pass,
  'user_email' => $email
);
 
$user_reg = wp_insert_user($userdata);
 
if(is_wp_error($user_reg)) {
    exit_with($user_reg->get_error_message());
}
else {
    // 保存用户其他信息
    $user_id = $user_reg;
    foreach ($_POST as $key => $value) {
        if (strpos($key, 'user_') === 0) {
            continue;
        }
        add_user_meta($user_id, $key, $value);
    }

    // 删掉验证码
    delete_option('verify:'.$mobile);

    response_with($email);
}
